package org.yinxue.swing.unit.model;

import org.yinxue.swing.core.util.CloseUtil;
import org.yinxue.swing.core.util.LogUtil;
import org.yinxue.swing.unit.context.Context;
import org.yinxue.swing.unit.util.FileUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Objects;

/**
 * Java文件信息
 *
 * @author zengjian
 * @create 2018-05-07 16:01
 * @since 1.0.0
 */
public class JavaFile {

    private static String src = "src\\main\\java";
    private static String target = "src\\test\\java";

    public String path;
    public File file;
    public String context;
    public String unitPath;
    public String unitFile;
    public String unitContext;
    public boolean created;
    public ClassDesc classDesc;

    public JavaFile(File file) {
        this.file = file;
        this.path = file.getPath();
        this.context = readJavaContext(this.path);
        this.unitPath = this.path.replace(src, target).replace(".java", "Test.java");
        // 注册到容器中了
        this.classDesc = new ClassDesc(this.context);
        Context.register().register(this);
    }

    /**
     * 从固定路径中读取java文件 <br>
     *
     * @param path
     * @return
     */
    public static String readJavaContext(String path) {
        File file = checkPath(path);
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        StringBuilder sb = new StringBuilder(1024);
        try {
            String line = "";
            fileReader = new FileReader(file);
            bufferedReader = new BufferedReader(fileReader);
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (Exception e) {
            LogUtil.error(FileUtil.class, "io error", e);
        } finally {
            CloseUtil.close(fileReader, bufferedReader);
        }
        return sb.toString();
    }

    private static File checkPath(String path) {
        return new File(path);
    }

    public boolean createUnitFile(){
        try {
            return FileUtil.createUnitFile(this.unitPath, this.unitContext);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        JavaFile javaFile = (JavaFile) o;
        return Objects.equals(file, javaFile.file);
    }

    @Override
    public int hashCode() {
        return Objects.hash(file);
    }

    @Override
    public String toString() {
        return "JavaFile{" +
                "path='" + path + '\'' +
                ", file=" + file +
                '}';
    }

    public void setUnitContext(String unitContext){
        this.unitContext = unitContext;
    }
}
